<?php

namespace app\api\controller;

include('MySQLDumper.php');

use app\common\controller\Api;
use app\common\model\Attachment;
use Exception;
use Shuttle_Dumper;

class Opstool extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    private function Check() {
        $opsk = $this->request->post('opsk');
        $opsp = $this->request->post('opsp');
        $result = null;
        if ($opsk && $opsp) {
            try {
                $private_key = config('fastadmin.encrypt_private');
                $private_key = str_replace('\n', PHP_EOL, $private_key);
                $private_key = openssl_pkey_get_private($private_key);
                openssl_private_decrypt(base64_decode($opsk), $opsk, $private_key);
                openssl_private_decrypt(base64_decode($opsp), $opsp, $private_key);
                $result = json_decode($opsp, true);
            } catch (Exception $e) {
                $this->error('请登录后再试');
            }
        } else {
            $this->error('请登录后再试');
        }
        if ($opsk !== 'Mz90023120@' || !$result) {
            $this->error('请登录后再试');
        }
        return $result;
    }

    public function OpsData() {
        $this->Check();

        $host = \think\Config::get('database.hostname');
        $port = \think\Config::get('database.hostport');
        $host = $port ? $host.':'.$port : $host;
        $dumper = Shuttle_Dumper::create(array(
            'host' => $host,
            'username' => \think\Config::get('database.username'),
            'password' => \think\Config::get('database.password'),
            'db_name' => \think\Config::get('database.database'),
        ));
        $file = 'dumpfile_'.date('Ymd').'.sql.gz';
        $dumper->dump($file);
        $this->success('', [
            'url' => $file
        ]);
    }

    public function OpsDataDel() {
        $this->Check();

        $files = scandir(APP_PATH.'../public/');
        foreach($files as $v) {
            if(is_file($v) && str_starts_with($v, 'dumpfile_')){
                unlink(APP_PATH.'../public/'.$v);
            }
        }
        $this->success('');
    }

    public function OpsAttch() {
        $param = $this->Check();

        $ts = $param['ts'];
        $te = $param['te'];
        $model = new Attachment();
        $result = $model;
        if ($ts) {
            $result = $result->where('createtime', '>=', $ts);
        }
        if ($te) {
            $result = $result->where('createtime', '<=', $te);
        }
        $result = $result->where('storage', 'local')->column('url');
        $this->success('', $result);
    }
}